#include <iostream>
#include <string>
#include <unordered_map>
#include "Log.hpp"

const std::string defaultconfpath = "./Dict.txt";
const std::string seq = ": ";

class Dict_serve
{
private:
    bool Load()
    {
        std::ifstream in(_conf_filepath);
        if (!in.is_open())
        {
            LOG(FATAL, "open %s error", _conf_filepath.c_str());
            return false;
        }
        std::string line;
        while (std::getline(in, line))
        {
            if (line.empty())
                continue;
            auto pos = line.find(seq);
            if (pos == std::string::npos)
                continue;
            std::string word = line.substr(0, pos);
            if (word.empty())
                continue;
            std::string han = line.substr(pos + seq.size());
            if (han.empty())
                continue;
            LOG(DEBUG, "load %s %s success", word.c_str(), han.c_str());
            _dict.insert({word, han});
        }
        in.close();
        LOG(DEBUG, "load %s success", _conf_filepath.c_str());
        return true;
    }

public:
    Dict_serve(const std::string &path = defaultconfpath) : _conf_filepath(path)
    {
        Load();
    }
    std::string translate(const std::string &word)
    {
        auto iter = _dict.find(word);
        if (iter == _dict.end())
            return "nofind(未找到)";
        // return _dict[word];
        return iter->second;
    }

private:
    std::unordered_map<std::string, std::string> _dict;
    std::string _conf_filepath;
};